﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DAL;
using Models;

namespace 包覆门.HanderManager
{
    public partial class HanderEditing : Form
    {
        public HanderEditing()
        {
            InitializeComponent();
        }

        public bool IsNew { get; set; }//是否新增
        public string EditingId { get; set; }//编辑用户id
        public HanderDAL dal = new HanderDAL();
        //保存
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateData()) return;
            Hander h = new Hander();
            if (IsNew)
            {
                h.Hname = this.tbHname.Text;
                h.Hprice = Convert.ToDecimal(this.tbPrice.Text);
                int result = dal.SaveData(h);
                if (result == 1)
                {
                    MessageBox.Show("保存成功");
                    DialogResult = DialogResult.OK;
                }
                else {
                    MessageBox.Show("保存失败");
                    DialogResult = DialogResult.No;
                }
            }
            else {
                h.Hid =Convert.ToInt32( EditingId);
                h.Hname = this.tbHname.Text;
                h.Hprice = Convert.ToDecimal(this.tbPrice.Text);
                int result = dal.UpdateData(h);
                if (result == 1)
                {
                    MessageBox.Show("保存成功");
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("保存失败");
                    DialogResult = DialogResult.No;
                }
            }
        }
        //拉手验证
        public bool ValidateData() {
            bool flag = true;
            if(String.IsNullOrWhiteSpace(this.tbHname.Text)){
                flag = false;
                MessageBox.Show("名称不能为空");
            }
            if (String.IsNullOrWhiteSpace(this.tbPrice.Text))
            {
                flag = false;
                MessageBox.Show("价格不能为空");
            }
                return flag;
        }
        //取消
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.No;
        }

        private void HanderEditing_Load(object sender, EventArgs e)
        {
            if (IsNew) { } else {
                Hander h = dal.GetHanderById(EditingId);
                this.tbHname.Text = h.Hname;
                this.tbPrice.Text = h.Hprice.ToString() ;
            }
        }

        private void tbPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == '.' || e.KeyChar == 8))
            {
                e.Handled = true;
            }  
        }
    }
}
